package com.bosssoft.boss_exam_web.Controller;


import com.bosssoft.boss_exam_core.enums.ResultCode;
import com.bosssoft.boss_exam_core.exception.DeleteEntityException;
import com.bosssoft.boss_exam_core.exception.QueryDataException;
import com.bosssoft.boss_exam_core.exception.ReflectionException;
import com.bosssoft.boss_exam_core.exception.UpdateEntityException;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_core.validator.Order;
import com.bosssoft.boss_exam_core.validator.Sort;
import com.bosssoft.boss_exam_db.entity.Company;
import com.bosssoft.boss_exam_db.entity.MyGroup;
import com.bosssoft.boss_exam_db.service.busines.CompanyService;
import com.bosssoft.boss_exam_db.service.busines.GroupService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import com.bosssoft.boss_exam_web.common.annotation.LoginApplicant;
import com.bosssoft.boss_exam_web.model.dto.CompanyDTO;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Validated
@Slf4j
@Api(value="公司控制器")
public class CompanyController {

    // 引入公司服务
    @Autowired
    private CompanyService companyService;

    // 引入集团服务
    @Autowired
    private GroupService groupService;

    @ApiOperation(value="公司查询", notes="可根据公司名称、所属集团名称查询公司" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="companyName", value="公司名称", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="groupName", value="集团名称", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="page", value="当前页码", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="limit", value="每页显示条数", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="sort", value="排序依据", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="order", value="排序方式", dataType = "String", required=false, dataTypeClass=String.class)
    })
    @GetMapping("/admin/company/list")
    public Object list(@LoginAdmin String adminId,
                       @RequestParam String companyName,
                       @RequestParam String groupName,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if ( adminId == null) {
            return ResponseUtil.unlogin();
        }
        PageInfo<Company> companyPageInfo = companyService.queryByCondition(companyName,groupName,page, limit, sort, order);
        if(companyPageInfo==null){
            log.error("【业余错误】，查询pageInfo为空");
            throw new QueryDataException();
        }
        long total = companyPageInfo.getTotal();
        List<Company> list = companyPageInfo.getList();
        List<CompanyDTO> companyDtoList = list.stream().map(company -> {
            MyGroup belongGroup = null;
            try {
                String groupId= company.getGroupId();
                if(groupId!=null){
                    belongGroup = groupService.selectByKey(groupId);
                }
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                log.error("【系统错误】 反射操作异常" + e);
                throw new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
            } catch (Exception e) {
                log.error("【业务错误】 读取集团异常" + e);
                throw new QueryDataException();
            }
            CompanyDTO companyDto = new CompanyDTO(belongGroup);
            //拷贝一份公司信息给dto对象
            BeanUtils.copyProperties(company, companyDto);
            return companyDto;
        }).collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("total", companyDtoList.size());
        data.put("items", companyDtoList);
        return ResponseUtil.ok(data);
    }

    @ApiOperation(value="公司添加", notes="添加公司" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="company", value="公司对象json", dataType = "Company", required=true, dataTypeClass= Company.class),
    })
    @PostMapping("/admin/company/create")
    public Object create(@LoginAdmin String adminId, @RequestBody Company company) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = companyService.saveNotNull(company);
        if(recordNum==1){
            return ResponseUtil.ok(company);
        }else{
            log.error("【系统错误】 保存公司失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="公司详细信息查询", notes="可根据公司的ID查询详情" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="公司ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/admin/company/read")
    public Object read(@LoginAdmin String  adminId, @NotNull Integer id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Company company = null;
        try {
            company = companyService.selectByKey(id);
        }  catch (NoSuchMethodException | InvocationTargetException |IllegalAccessException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e){
            log.error("【业务错误】 读取公司异常"+e);
            throw  new QueryDataException();
        }
        return ResponseUtil.ok(company);
    }


    @ApiOperation(value="公司更新", notes="更新公司" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="company", value="公司对象json，必须携带公司ID", dataType = "Company", required=true, dataTypeClass= Company.class),
    })
    @PostMapping("/admin/company/update")
    public Object update(@LoginAdmin String  adminId, @RequestBody Company company) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = companyService.updateNotNull(company);
        if(recordNum==1){
            return ResponseUtil.ok(company);
        }else{
            log.error("【系统错误】 保存公司失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="公司删除", notes="可根据公司的ID逻辑删除公司" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="公司ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @PostMapping("/admin/company/delete")
    public Object delete(@LoginAdmin String adminId, @RequestParam String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        try {
            Company company = new Company();
            company.setId(id);
            int recordNum = companyService.deleteCascade(company);
            if(recordNum==1){
                return ResponseUtil.ok();
            }else {
                log.info("【业务错误】 逻辑删除公司失败");
                throw  new DeleteEntityException();
            }
        } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }
    }

    @ApiOperation(value="查询集团", notes="根据集团ID查询所有公司" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupId", value="集团ID", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/pc/company/queryCompanys")
    public Object getAllGroup(@LoginApplicant String applicantId, @RequestParam String groupId){
        if (applicantId == null) {
            return ResponseUtil.unlogin();
        }
        if(StringUtils.isEmpty(groupId)){
            return ResponseUtil.badArgument();
        }
        List<Company> companyList =  companyService.queryAllCompanyByGroupId(groupId);
        return ResponseUtil.ok(companyList);
    }
}
